package com.feign.util;

import com.feign.util.pojo.ShellRunData;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * TODO
 *
 * @Description 运行命令行命令的类
 * @Author ZW
 * @Date 2022/12/30 18:47
 **/
@Slf4j
public class ShellRun {
    /**
     * 判断系统是否为windows
     *
     * @return 是否为windows系统
     */
    private boolean osIsWindows() {
        return System.getProperty("os.name").toLowerCase().contains("windows");
    }

    /**
     * 运行命令
     * @param orders 命令
     * @return 运行状态
     */
    @SuppressWarnings("unchecked")
    private ShellRunData run(String[] orders){
        log.info("orders : {}" , Arrays.toString(orders));
        Process process = null;
        ShellRunData shellRunData = new ShellRunData();

        Date start = null;
        Date end = null;
        try {
            process = Runtime.getRuntime().exec(orders);
            SystemStream stream1 = new SystemStream(process.getInputStream());
            SystemStream stream2 = new SystemStream(process.getErrorStream());
            start = new Date();
            ExecutorService service = Executors.newFixedThreadPool(2);
            Future<String> submit1 = service.submit(stream1);
            Future<String> submit2 = service.submit(stream2);
            shellRunData.setStandardOut(submit1.get());
            shellRunData.setErrorOut(submit2.get());
            service.shutdown();
            end = new Date();
            shellRunData.setRunTime((int) (end.getTime() - start.getTime()));
            shellRunData.setRunStart(true);

        } catch (InterruptedException | ExecutionException | IOException e) {
            log.info("脚本运行失败 {}", Arrays.toString(orders));
            throw new RuntimeException(e);
        }
        log.info("shellRunData:{}" ,shellRunData);
        return shellRunData;
    }

    /**
     * 根据不同机型设置脚本头
     * @param data 运行脚本的内容
     * @return
     */
    protected ShellRunData runShell(String ...data){
        String[] shellStringData = new String[data.length+2];
        if (Boolean.TRUE.equals(osIsWindows())){
            shellStringData[0] ="cmd";
            shellStringData[1] ="/c";
        }else{
            shellStringData[0] ="/bin/sh";
            shellStringData[1] ="-c";
        }
        System.arraycopy(data, 0, shellStringData, 2, data.length);
        return  run(shellStringData);
    }
}
